#!/bin/bash

color_red=$(tput setaf 1 || tput AF 1)
color_green=$(tput setaf 2 || tput AF 2)
color_yellow=$(tput setaf 3 || tput AF 3)
color_reset=$(tput sgr0 || tput me)

function color_text() {
    local color=$1
    local text=$2
    case $color in
        red)
                >&2 echo -e "${color_red}${text}${color_reset}"
                ;;
        green)
                >&2 echo -e "${color_green}${text}${color_reset}"
                ;;
        yellow)
                #>&2 echo -e "${common_text}${color_yellow}${text}${color_reset}"
                >&2 echo -e "${color_yellow}${text}${color_reset}"
                ;;
       default)
                >&2 echo "${text}"
    esac
}

# 使用: log INFO "This is log INFO message"
function log() {
    local -r level=$1
    local -r message=$2
    local -r timestamp=$(date +'%Y-%m-%d %H:%M:%S')
    local -r script_name="$(basename "$0")"
    common_text="${timestamp} [${level}] [$script_name] "
    echo -e "${common_text}\c"
    case $level in
        INFO)
            color_text green "${message}"
            ;;
        ERROR)
            color_text red "${message}"
            ;;
        WARN)
            color_text yellow "${message}"
            ;;
        *)
            color_text default "${message}"
    esac
}

